//+------------------------------------------------------------------+
//|                                                      SuperTrend.mq5 |
//|                                                                     |
//|                                                                     |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024"
#property link      ""
#property version   "1.00"

// External Parameters (原外部参数)
input string   EAComment = "王者无敌";        // EA注释
input bool     DynamicSwitch = false;        // 动态开关 (原DongTaiKaiGuan)
input int      VolatilityFactor = 59;        // 波动率因子 (原BoDongLu)
input int      AdaptiveFactor = 68;          // 自适应因子 (原ZiShiYing)
input int      OpenPositionFactor = 10;      // 开仓因子 (原KaiCangYinZi)
input int      ClosePositionFactor = 15;     // 平仓因子 (原PingCangYinZi)
input int      ClosePositionFactor2 = 31;    // 平仓因子2 (原PingCangYinZi2)
input int      SpeedFactor = 9;              // 速度因子 (原SuDuYinZi)
input int      ProfitFactor = 15;            // 盈利因子 (原YingLiYinZi)
input double   LotSize = 0.1;                // 交易手数 (原Lots)
input bool     RiskSwitch = false;           // 风险开关 (原FuliKaiGuan)
input int      RiskPercent = 10;             // 风险百分比 (原Risk)
input string   AsianSessionStrategy = "";    // 亚盘策略 (原一一一一亚盘策略一一一)
input bool     AsianSessionSwitch = false;   // 亚盘开关 (原ZaoPan)
input int      TimeStart = 1;                // 开始时间 (原Tima)
input int      TimeEnd = 19;                 // 结束时间 (原Timb)
input int      StopLoss = 114;               // 止损点数 (原StopLos)

// Global Variables (原全局变量)
int       g_buyCount = 0;                    // 多单计数 (原by_in_1)
int       g_sellCount = 0;                   // 空单计数 (原by_in_2)
int       g_magicNumber = 19828668;          // 魔术数字 (原by_in_3)
int       g_slippage = 3;                    // 滑点 (原by_in_5)
bool      g_tradeEnabled = true;             // 交易启用标志 (原by_bo_6)
double    g_buyLot = 0;                      // 多单手数 (原by_do_7)
double    g_sellLot = 0;                     // 空单手数 (原by_do_8)
double    g_currentPrice = 0;                // 当前价格 (原by_do_9)
double    g_stopLossPrice = 0;               // 止损价格 (原by_do_10)
int       g_pointValue = 10;                 // 点值 (原by_in_11)
int       g_orderTicket = -1;                // 订单号 (原by_in_12)
int       g_retryCount = 0;                  // 重试计数 (原by_in_13)
double    g_minLot = 0;                      // 最小手数 (原by_do_14)
double    g_maxLot = 0;                      // 最大手数 (原by_do_15)
double    g_takeProfit = 0;                  // 止盈价格 (原by_do_16)
int       g_digits = 0;                      // 小数位数 (原by_in_17)
double    g_ask = 0;                         // 卖价 (原by_do_18)
double    g_bid = 0;                         // 买价 (原by_do_19)
double    g_spreadValue = 0;                 // 点差值 (原g_highPrice)
double    g_lowPrice = 0;                    // 最低价 (原by_do_21)
int       g_buyOrders = 0;                   // 多单数量 (原by_in_21)
int       g_sellOrders = 0;                  // 空单数量 (原by_in_22)
double    g_buyVolume = 0;                   // 多单量 (原by_do_23)
double    g_sellVolume = 0;                  // 空单量 (原by_do_24)
double    g_buyLotSize = 0;                  // 多单手数 (原by_do_25)
double    g_sellLotSize = 0;                 // 空单手数 (原by_do_26)
double    g_buyProfit = 0;                   // 多单利润 (原by_do_27)
double    g_sellProfit = 0;                  // 空单利润 (原by_do_28)
double    g_totalProfit = 0;                 // 总利润 (原by_do_29)
double    g_totalVolume = 0;                 // 总交易量 (原by_do_30)
double    g_buyOpenPrice = 0;                // 多单开仓价 (原by_do_32)
double    g_sellOpenPrice = 0;               // 空单开仓价 (原by_do_33)
double    g_highPrice2 = 0;                  // 最高价2 (原by_do_34)
double    g_lowPrice2 = 0;                   // 最低价2 (原by_do_35)
double    g_closePrice = 0;                  // 收盘价 (原by_do_36)
datetime  g_buyOpenTime = 0;                 // 多单开仓时间 (原by_lo_37)
datetime  g_currentTime = 0;                 // 当前时间 (原by_lo_38)
datetime  g_sellOpenTime = 0;                // 空单开仓时间 (原by_lo_39)
datetime  g_lastBarTime = 0;                 // 最后K线时间 (原by_lo_40)
datetime  g_buyTime = 0;                     // 多单时间 (原by_lo_41)
datetime  g_sellTime = 0;                    // 空单时间 (原by_lo_42)
long      g_timeFrame = 0;                   // 时间周期 (原by_lo_43)
string    g_symbol;                          // 交易品种 (原by_st_44)
int       g_spread = 0;                      // 点差 (原by_in_45)
int       g_retryLimit = 1;                  // 重试限制 (原by_in_46)
string    g_errorMessage;                    // 错误信息 (原by_st_47)
datetime  g_expiryDate = D'2027.03.02';      // 过期日期 (原by_lo_49)
bool      g_isTradeAllowed = true;           // 允许交易标志 (原by_bo_51)
bool      g_isSuperTrendEnabled = true;      // 超级趋势启用标志 (原by_bo_52)
double    g_adaptiveHigh = 0;                // 自适应因子最高价
double    g_adaptiveLow = 0;                 // 自适应因子最低价

// 最后标记的K线时间
datetime g_timeOfLastMarkedBar;

// 在全局变量区添加：
datetime g_lastDrawBoxTime = 0;
double g_superTrendValue = 0;
int g_lastPeriod = 0;           // 上次的时间周期

//+------------------------------------------------------------------+
//| Expert initialization function                                     |
//+------------------------------------------------------------------+
int OnInit()
{
    // 初始化最后标记的K线时间
    g_timeOfLastMarkedBar = iTime(_Symbol, PERIOD_CURRENT, 1);
    g_lastDrawBoxTime = g_timeOfLastMarkedBar;
    g_lastPeriod = Period();
    
    // 初始化点值计算
    g_minLot = MathPow(0.1, _Digits);
    
    // 根据货币对和位数设置点值
    if(_Digits == 5 || _Digits == 3)
    {
        g_pointValue = 10;
    }
    
    // 黄金特殊处理
    if(StringFind(_Symbol, "XAU") >= 0 || StringFind(_Symbol, "GOLD") >= 0)
    {
        if(_Digits == 2)
            g_pointValue = 10;
        else if(_Digits == 3)
            g_pointValue = 100;
        else if(_Digits == 4)
            g_pointValue = 1000;
    }

    Print("g_pointValue: ", g_pointValue,"_Digits: ", _Digits,"g_minLot: ", g_minLot);
    //BTC特殊处理
    if(StringFind(_Symbol, "BTC") >= 0)
    {
        if(_Digits == 2)
            g_pointValue = 10*100;
        else if(_Digits == 3)
            g_pointValue = 100*100;
        else if(_Digits == 4)
            g_pointValue = 1000*100;
    }
    
    // 获取交易品种信息
    g_digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
    
    // 设置图表属性
    ChartSetInteger(0, CHART_SHOW_GRID, true);
    
    // 创建交易按钮
    string buttonName = "TradeButton";
    if(!ButtonCreate(0, buttonName, 0, 0, 15, 330, 245, 0, "", "Arial", 9, clrLightSlateGray, 0, clrDimGray, false, false, false, false, 0))
    {
        Print("Failed to create button: ", GetLastError());
        return INIT_FAILED;
    }
    
    // 初始化其他变量
    g_symbol = _Symbol;
    g_currentTime = TimeCurrent();
    g_lastBarTime = iTime(_Symbol, PERIOD_CURRENT, 1);
    
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| 创建按钮函数                                                       |
//+------------------------------------------------------------------+
bool ButtonCreate(const long chart_id,      // 图表ID
                 const string name,         // 按钮名称
                 const int sub_window,      // 子窗口号
                 const int x,               // X坐标
                 const int y,               // Y坐标
                 const int width,           // 宽度
                 const int height,          // 高度
                 const int corner,          // 角位置
                 const string text,         // 文本
                 const string font,         // 字体
                 const int font_size,       // 字体大小
                 const color text_color,    // 文本颜色
                 const color bg_color,      // 背景颜色
                 const color border_color,  // 边框颜色
                 const bool state,          // 状态
                 const bool back,           // 背景
                 const bool selection,      // 可选择
                 const bool hidden,         // 隐藏
                 const long z_order)        // 优先级
{
    if(!ObjectCreate(chart_id, name, OBJ_BUTTON, sub_window, 0, 0))
        return false;
        
    ObjectSetInteger(chart_id, name, OBJPROP_XDISTANCE, x);
    ObjectSetInteger(chart_id, name, OBJPROP_YDISTANCE, y);
    ObjectSetInteger(chart_id, name, OBJPROP_XSIZE, width);
    ObjectSetInteger(chart_id, name, OBJPROP_YSIZE, height);
    ObjectSetInteger(chart_id, name, OBJPROP_CORNER, corner);
    ObjectSetString(chart_id, name, OBJPROP_TEXT, text);
    ObjectSetString(chart_id, name, OBJPROP_FONT, font);
    ObjectSetInteger(chart_id, name, OBJPROP_FONTSIZE, font_size);
    ObjectSetInteger(chart_id, name, OBJPROP_COLOR, text_color);
    ObjectSetInteger(chart_id, name, OBJPROP_BGCOLOR, bg_color);
    ObjectSetInteger(chart_id, name, OBJPROP_BORDER_COLOR, border_color);
    ObjectSetInteger(chart_id, name, OBJPROP_BACK, back);
    ObjectSetInteger(chart_id, name, OBJPROP_STATE, state);
    ObjectSetInteger(chart_id, name, OBJPROP_SELECTABLE, selection);
    ObjectSetInteger(chart_id, name, OBJPROP_SELECTED, selection);
    ObjectSetInteger(chart_id, name, OBJPROP_HIDDEN, hidden);
    ObjectSetInteger(chart_id, name, OBJPROP_ZORDER, z_order);
    
    return true;
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                   |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    ObjectsDeleteAll(0, 23);
    ObjectDelete(0, "EURUSD");
    ObjectDelete(0, "EURUSD1");
    ObjectDelete(0, "EURUSD3");
    ObjectDelete(0, "EURUSD2");
    ObjectDelete(0, "点差");
}

//+------------------------------------------------------------------+
//| Expert tick function                                              |
//+------------------------------------------------------------------+
void OnTick()
{
    // 获取当前K线时间
    datetime currentBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
    int currentPeriod = Period();
    
    // 检查是否需要重绘箱体
    bool needRedraw = false;
    
    // 如果是新K线
    if(currentBarTime != g_lastDrawBoxTime)
    {
        needRedraw = true;
        g_lastDrawBoxTime = currentBarTime;
    }
    
    // 如果时间周期改变
    if(currentPeriod != g_lastPeriod)
    {
        needRedraw = true;
        g_lastPeriod = currentPeriod;
    }
    
    // 如果需要重绘，先清除旧的箱体
    if(needRedraw)
    {
        // 删除所有旧的箱体对象
        ObjectDelete(0, "AdaptiveBox");
        ObjectDelete(0, "SpeedBox");
        ObjectDelete(0, "BuyThresholdLine");
        ObjectDelete(0, "SellThresholdLine");
        ObjectDelete(0, "VolatilityLabel");
        
        // 绘制新的箱体
        DrawBoxes();
    }
    
    // 检查交易按钮状态
    CheckTradeButton();
    
    // 局部变量声明
    int         local_retryCount = 0;        // 重试计数 (原dfz_in_1)
    datetime    currentTime;                 // 当前时间 (原dfz_in_2)
    datetime    expiryTime;                  // 过期时间 (原dfz_do_3)
    double      highPrice;                   // 最高价 (原dfz_do_4)
    double      lowPrice;                    // 最低价 (原dfz_do_5)
    double      speedHighPrice;              // 速度因子最高价 (原dfz_do_6)
    double      speedLowPrice;               // 速度因子最低价 (原dfz_do_7)
    datetime    lastBarTime;                 // 最后K线时间 (原dfz_lo_8)
    double      closePrice;                  // 收盘价 (原dfz_do_9)
    double      currentClosePrice;           // 当前收盘价 (原dfz_do_10)
    double      speedHighPrice1;             // 速度因子最高价1 (原dfz_do_11)
    double      speedLowPrice1;              // 速度因子最低价1 (原dfz_do_12)
    double      superTrendValue;             // 超级趋势值 (原dfz_do_13)
    int         currentHour;                 // 当前小时 (原dfz_in_14)
    bool        isAsianSession;              // 是否亚盘时段 (原dfz_bo_15)
    
    // 交易相关变量
    int         orderType;                   // 订单类型 (原aa_in_1)
    int         buyOrderType = 0;            // 多单类型 (原aa_in_2)
    int         buyOrderIndex;               // 多单索引 (原aa_in_3)
    int         sellOrderType = 1;           // 空单类型 (原aa_in_4)
    int         sellOrderIndex;              // 空单索引 (原aa_in_5)
    int         buyCloseType = 0;            // 多单平仓类型 (原aa_in_6)
    int         buyCloseIndex;               // 多单平仓索引 (原aa_in_7)
    int         sellCloseType = 1;           // 空单平仓类型 (原aa_in_8)
    int         sellCloseIndex;              // 空单平仓索引 (原aa_in_9)
    int         buyCloseType2 = 0;           // 多单平仓类型2 (原aa_in_10)
    int         buyCloseIndex2;              // 多单平仓索引2 (原aa_in_11)
    int         sellCloseType2 = 1;          // 空单平仓类型2 (原aa_in_12)
    int         sellCloseIndex2;             // 空单平仓索引2 (原aa_in_13)

    // 初始化变量
    isAsianSession = false;
    orderType = 0;
    buyOrderType = 0;
    buyOrderIndex = 0;
    sellOrderType = 1;
    sellOrderIndex = 0;
    buyCloseType = 0;
    buyCloseIndex = 0;
    sellCloseType = 1;
    sellCloseIndex = 0;
    buyCloseType2 = 0;
    buyCloseIndex2 = 0;
    sellCloseType2 = 1;
    sellCloseIndex2 = 0;
    local_retryCount = 1;

    // 检查时间周期
    if(Period() == PERIOD_M5)
    {
        return;
    }

    // 获取点差
    g_spreadValue = (double)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
    g_isTradeAllowed = true;

    // 检查EA是否启用
    if(!MQLInfoInteger(MQL_TRADE_ALLOWED))
    {
        CreateLabel("启动", "请点击上方-自动交易-按钮", 9, "Arial", clrChocolate, 100, 100, 80);
        g_isTradeAllowed = false;
    }
    else
    {
        CreateLabel("启动", "", 10, "Arial", clrChocolate, 100, 100, 80);
    }

    // 检查交易是否允许
    if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED))
    {
        CreateLabel("启动", "请把允许实时自动交易打勾", 9, "Arial", clrChocolate, 100, 100, 80);
        g_isTradeAllowed = false;
    }
    else
    {
        CreateLabel("启动", "", 10, "Arial", clrChocolate, 100, 100, 80);
    }

    // 检查点差
    if(CheckSpread())
    {
        g_tradeEnabled = false;
        Print(TimeToString(TimeCurrent(), TIME_MINUTES), " ,点差过高! 当前点差: ", DoubleToString(g_spreadValue, 2));
    }
    else
    {
        g_tradeEnabled = true;
    }

    // 获取当前时间和价格数据
    currentTime = TimeCurrent();
    expiryTime = g_expiryDate;
    g_ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits);
    g_bid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits);

    // 获取高低点
    highPrice = NormalizeDouble(iHigh(_Symbol, PERIOD_CURRENT, iHighest(_Symbol, PERIOD_CURRENT, MODE_HIGH, AdaptiveFactor, 2)), _Digits);
    lowPrice = NormalizeDouble(iLow(_Symbol, PERIOD_CURRENT, iLowest(_Symbol, PERIOD_CURRENT, MODE_LOW, AdaptiveFactor, 2)), _Digits);
    speedHighPrice = NormalizeDouble(iHigh(_Symbol, PERIOD_CURRENT, iHighest(_Symbol, PERIOD_CURRENT, MODE_HIGH, SpeedFactor, 2)), _Digits);
    speedLowPrice = NormalizeDouble(iLow(_Symbol, PERIOD_CURRENT, iLowest(_Symbol, PERIOD_CURRENT, MODE_LOW, SpeedFactor, 2)), _Digits);

    g_adaptiveHigh = NormalizeDouble(highPrice, _Digits);
    g_adaptiveLow = NormalizeDouble(lowPrice, _Digits);

    // 统计交易
    CountTrades();

    // 获取时间价格数据
    lastBarTime = iTime(_Symbol, PERIOD_CURRENT, 1);
    closePrice = NormalizeDouble(iClose(_Symbol, PERIOD_CURRENT, 1), _Digits);
    g_currentTime = iTime(_Symbol, PERIOD_CURRENT, 1);
    g_lastBarTime = iTime(_Symbol, PERIOD_CURRENT, 1);
    currentClosePrice = NormalizeDouble(iClose(_Symbol, PERIOD_CURRENT, 1), _Digits);
    speedHighPrice1 = NormalizeDouble(iHigh(_Symbol, PERIOD_CURRENT, iHighest(_Symbol, PERIOD_CURRENT, MODE_HIGH, SpeedFactor, 1)), _Digits);
    speedLowPrice1 = NormalizeDouble(iLow(_Symbol, PERIOD_CURRENT, iLowest(_Symbol, PERIOD_CURRENT, MODE_LOW, SpeedFactor, 1)), _Digits);

    // 计算超级趋势值
    if(speedHighPrice1 - currentClosePrice > 0)
    {
        //越大越靠近上方
        g_superTrendValue = CalculateSuperTrend(speedHighPrice1, closePrice, speedHighPrice1, speedLowPrice1);
    }

    // 检查超级趋势状态
    if(g_superTrendValue == 100)
    {
        g_isTradeAllowed = false;
        g_isSuperTrendEnabled = false;
    }
    else
    {
        g_isSuperTrendEnabled = true;
    }

    // 设置时间周期
    switch(Period())
    {
        case PERIOD_M15: g_timeFrame = 910; break;
        case PERIOD_M30: g_timeFrame = 1810; break;
        case PERIOD_H1: g_timeFrame = 3610; break;
        case PERIOD_H4: g_timeFrame = 14410; break;
    }

    // 检查交易条件
    if(StringFind(_Symbol, "GBPCAD") != 0)
    {
        // 检查多单开仓条件
        if(CheckBuyEntry(currentClosePrice, lowPrice, speedLowPrice)
           && g_buyOpenTime != g_currentTime && 
           g_ask < g_pointValue * 5 * g_minLot + currentClosePrice && local_retryCount == 1)
        {
            OpenBuy();
        }

        // 检查空单开仓条件
        if(CheckSellEntry(highPrice, currentClosePrice, speedHighPrice)
           && g_sellOpenTime != g_lastBarTime && g_isTradeAllowed &&
           g_ask > currentClosePrice - g_pointValue * 5 * g_minLot && local_retryCount == 1)
        {
            OpenSell();
        }

        // 检查多单二次开仓条件
        if(CheckBuySecondEntry(currentClosePrice, highPrice, lowPrice, lowPrice, g_bid)
           && g_buyOpenTime != g_currentTime && currentTime - lastBarTime <= g_timeFrame && g_isTradeAllowed &&
           g_ask < g_pointValue * 5 * g_minLot + currentClosePrice && local_retryCount == 1)
        {
            OpenBuy();
        }

        // 检查空单二次开仓条件
        if(CheckSellSecondEntry(currentClosePrice, highPrice, lowPrice, highPrice, g_ask)
           && g_sellOpenTime != g_lastBarTime && currentTime - lastBarTime <= g_timeFrame && g_isTradeAllowed &&
           g_ask > currentClosePrice - g_pointValue * 5 * g_minLot && local_retryCount == 1)
        {
            OpenSell();
        }
    }

    // 检查亚盘时段
    MqlDateTime dt;
    TimeToStruct(TimeLocal(), dt);
    currentHour = dt.hour;
    isAsianSession = false;
    
    if(MQLInfoInteger(MQL_TESTER))
    {
        TimeToStruct(TimeCurrent(), dt);
        if(dt.hour <= TimeStart || dt.hour >= TimeEnd)
        {
            isAsianSession = true;
        }
    }
    else
    {
        if(currentHour >= 3 && currentHour <= 9)
        {
            isAsianSession = true;
        }
    }

    // 亚盘交易逻辑
    if(AsianSessionSwitch && StringFind(_Symbol, "GBPCAD") >= 0 && isAsianSession)
    {
        // 亚盘多单开仓条件
        if(CheckBuyEntry(currentClosePrice, lowPrice, speedLowPrice)
           && g_buyOpenTime != g_currentTime && g_isTradeAllowed &&
           speedHighPrice - speedLowPrice < g_pointValue * 180 * g_minLot &&
           g_ask < g_pointValue * 5 * g_minLot + currentClosePrice && local_retryCount == 1)
        {
            OpenBuy();
        }

        // 亚盘空单开仓条件
        if(CheckSellEntry(highPrice, currentClosePrice, speedHighPrice)
           && g_sellOpenTime != g_lastBarTime && g_isTradeAllowed &&
           speedHighPrice - speedLowPrice < g_pointValue * 180 * g_minLot &&
           g_ask > currentClosePrice - g_pointValue * 5 * g_minLot && local_retryCount == 1)
        {
            OpenSell();
        }

        // 亚盘多单二次开仓条件
        if(CheckBuySecondEntry(currentClosePrice, highPrice, lowPrice, lowPrice, g_bid)
           && g_buyOpenTime != g_currentTime && currentTime - lastBarTime <= g_timeFrame && g_isTradeAllowed &&
           g_ask < g_pointValue * 5 * g_minLot + currentClosePrice && local_retryCount == 1)
        {
            OpenBuy();
        }

        // 亚盘空单二次开仓条件
        if(CheckSellSecondEntry(currentClosePrice, highPrice, lowPrice, highPrice, g_ask)
           && g_sellOpenTime != g_lastBarTime && currentTime - lastBarTime <= g_timeFrame && g_isTradeAllowed &&
           g_ask > currentClosePrice - g_pointValue * 5 * g_minLot && local_retryCount == 1)
        {
            OpenSell();
        }
    }

    // 平仓逻辑
    if(g_timeOfLastMarkedBar < lastBarTime)
    {
        // 多单平仓条件
        if(CheckBuyClose(g_buyOrders, currentClosePrice, speedHighPrice, g_superTrendValue,
           ClosePositionFactor, currentTime, g_retryLimit, g_retryLimit, g_retryLimit, g_retryLimit, expiryTime))
        {
            CloseBuyOrders();
        }

        // 空单平仓条件
        if(CheckSellClose(g_sellOrders, currentClosePrice, speedLowPrice, g_superTrendValue,
           ClosePositionFactor, currentTime, g_retryLimit, g_retryLimit, g_retryLimit, g_retryLimit, expiryTime))
        {
            CloseSellOrders();
        }

        // 多单盈利平仓条件
        if(CheckBuyProfitClose(g_buyOrders, currentClosePrice, g_buyOpenPrice,
           ProfitFactor, g_pointValue, g_minLot, currentTime, g_retryLimit, g_retryLimit, g_retryLimit, g_retryLimit, expiryTime))
        {
            CloseBuyOrders();
        }

        // 空单盈利平仓条件
        if(CheckSellProfitClose(g_sellOrders, currentClosePrice, g_sellOpenPrice,
           ProfitFactor, g_pointValue, g_minLot, currentTime, g_retryLimit, g_retryLimit, g_retryLimit, g_retryLimit, expiryTime))
        {
            CloseSellOrders();
        }

        // 多单二次平仓条件
        if(CheckBuySecondClose(g_buyOrders, g_buyProfit, g_superTrendValue,
           ClosePositionFactor2, currentTime, g_retryLimit, g_retryLimit, g_retryLimit, g_retryLimit, expiryTime))
        {
            CloseBuyOrders();
        }

        // 空单二次平仓条件
        if(CheckSellSecondClose(g_sellOrders, g_sellProfit, g_superTrendValue,
           ClosePositionFactor2, currentTime, g_retryLimit, g_retryLimit, g_retryLimit, g_retryLimit, expiryTime))
        {
            CloseSellOrders();
        }

        g_timeOfLastMarkedBar = lastBarTime;
    }

    // 创建EA运行状态标签
    CreateLabel("sd2", "EA运行状态：", 9, "Arial", clrMagenta, CORNER_LEFT_UPPER, 10, 60);

    // 根据交易状态显示不同信息
    if(!g_isTradeAllowed)
    {
        CreateLabel("sd3", "↓ ---运行失败，有以下原因--- ↓", 9, "Arial", clrYellow, CORNER_LEFT_UPPER, 105, 60);
        
        // 删除所有交易信息标签
        ObjectDelete(0, "多亏1");
        ObjectDelete(0, "多数1");
        ObjectDelete(0, "多量1");
        ObjectDelete(0, "分界1");
        ObjectDelete(0, "空亏1");
        ObjectDelete(0, "空数1");
        ObjectDelete(0, "空量1");
        ObjectDelete(0, "多亏2");
        ObjectDelete(0, "多数2");
        ObjectDelete(0, "多量2");
        ObjectDelete(0, "空亏2");
        ObjectDelete(0, "空数2");
        ObjectDelete(0, "空量2");
    }
    else
    {
        CreateLabel("sd3", "-----运行正常-----", 10, "Arial", clrLime, CORNER_LEFT_UPPER, 105, 60);
        
        // 创建多单信息标签
        CreateLabel("多亏1", "多单盈亏 : ", 9, "Arial", clrDodgerBlue, CORNER_LEFT_UPPER, 105, 80);
        CreateLabel("多数1", "多单手数 : ", 9, "Arial", clrDodgerBlue, CORNER_LEFT_UPPER, 105, 100);
        CreateLabel("多量1", "多单数量 : ", 9, "Arial", clrDodgerBlue, CORNER_LEFT_UPPER, 105, 120);
        CreateLabel("分界1", "------------------------", 9, "Arial", clrOrangeRed, CORNER_LEFT_UPPER, 105, 140);
        
        // 创建空单信息标签
        CreateLabel("空亏1", "空单盈亏 : ", 9, "Arial", clrOrangeRed, CORNER_LEFT_UPPER, 105, 160);
        CreateLabel("空数1", "空单手数 : ", 9, "Arial", clrOrangeRed, CORNER_LEFT_UPPER, 105, 180);
        CreateLabel("空量1", "空单数量 : ", 9, "Arial", clrOrangeRed, CORNER_LEFT_UPPER, 105, 200);
        
        // 创建多单数值标签
        CreateLabel("多亏2", DoubleToString(g_buyProfit, 2), 9, "Arial", clrDodgerBlue, CORNER_LEFT_UPPER, 175, 80);
        CreateLabel("多数2", DoubleToString(g_buyVolume, 2), 9, "Arial", clrDodgerBlue, CORNER_LEFT_UPPER, 175, 100);
        CreateLabel("多量2", IntegerToString(g_buyOrders), 9, "Arial", clrDodgerBlue, CORNER_LEFT_UPPER, 175, 120);
        
        // 创建空单数值标签
        CreateLabel("空亏2", DoubleToString(g_sellProfit, 2), 9, "Arial", clrOrangeRed, CORNER_LEFT_UPPER, 175, 160);
        CreateLabel("空数2", DoubleToString(g_sellVolume, 2), 9, "Arial", clrOrangeRed, CORNER_LEFT_UPPER, 175, 180);
        CreateLabel("空量2", IntegerToString(g_sellOrders), 9, "Arial", clrOrangeRed, CORNER_LEFT_UPPER, 175, 200);
    }

    // 检查亚盘开关
    if(!AsianSessionSwitch && StringFind(_Symbol, "GBPCAD") >= 0)
    {
        Alert("请把亚盘开关打开");
        Sleep(100000);
    }

    // 更新交易按钮状态
    UpdateTradeButton();

    // 在面板上展示CalculateSuperTrend关键参数
    int panelX = 10;
    int panelY = 230;
    int panelStep = 22;
    // CreateLabel("st_param1", "speedHighPrice1: " + DoubleToString(speedHighPrice1, _Digits), 9, "Consolas", clrBlue, CORNER_LEFT_UPPER, panelX, panelY);
    // CreateLabel("st_param2", "closePrice: " + DoubleToString(closePrice, _Digits), 9, "Consolas", clrBlue, CORNER_LEFT_UPPER, panelX, panelY + panelStep);
    // CreateLabel("st_param3", "speedLowPrice1: " + DoubleToString(speedLowPrice1, _Digits), 9, "Consolas", clrBlue, CORNER_LEFT_UPPER, panelX, panelY + 2 * panelStep);
    CreateLabel("st_result", "superTrendValue: " + DoubleToString(g_superTrendValue, 2), 9, "Consolas", clrMagenta, CORNER_LEFT_UPPER, panelX, panelY + 3 * panelStep);
}

//+------------------------------------------------------------------+
//| 创建标签函数                                                       |
//+------------------------------------------------------------------+
void CreateLabel(string name, string text, int size, string font, color clr, int corner, int x, int y)
{
    if(!ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0))
        return;
        
    ObjectSetString(0, name, OBJPROP_TEXT, text);
    ObjectSetInteger(0, name, OBJPROP_FONTSIZE, size);
    ObjectSetString(0, name, OBJPROP_FONT, font);
    ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
    ObjectSetInteger(0, name, OBJPROP_CORNER, corner);
    ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
    ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
}

//+------------------------------------------------------------------+
//| 检查点差函数                                                       |
//+------------------------------------------------------------------+
bool CheckSpread()
{
    double spread = (double)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
    bool isTesting = MQLInfoInteger(MQL_TESTER);
    
    if(isTesting)
    {
        if((StringFind(_Symbol, "GBPUSD") >= 0 && spread > g_pointValue * 2.5) ||
           ((StringFind(_Symbol, "XAUUSD") >= 0 || StringFind(_Symbol, "GOLD") >= 0) && spread > g_pointValue * 3.5) ||
           (StringFind(_Symbol, "USDJPY") >= 0 && spread > g_pointValue * 2.0) ||
           (StringFind(_Symbol, "GBPCAD") >= 0 && spread > g_pointValue * 4.0))
        {
            CreateLabel("回测", "您回测点差过大，请照ECN平台点差设置", 9, "Arial", clrChocolate, 100, 100, 200);
            return true;
        }
    }
    else
    {
        if((StringFind(_Symbol, "GBPUSD") >= 0 && spread > g_pointValue * 2.6) ||
           ((StringFind(_Symbol, "XAUUSD") >= 0 || StringFind(_Symbol, "GOLD") >= 0) && spread > g_pointValue * 3.7) ||
           (StringFind(_Symbol, "USDJPY") >= 0 && spread > g_pointValue * 2.3) ||
           (StringFind(_Symbol, "GBPCAD") >= 0 && spread > g_pointValue * 5.0))
        {
            CreateLabel("点差", "点差过高 : ", 10, "Consolas", clrRed, CORNER_LEFT_UPPER, 10, 30);
            CreateLabel("点差2", DoubleToString(spread, 2), 10, "Consolas", clrRed, CORNER_LEFT_UPPER, 85, 30);
            return true;
        }
        else
        {
            CreateLabel("点差", "点    差 : ", 10, "Consolas", clrDodgerBlue, CORNER_LEFT_UPPER, 10, 30);
            CreateLabel("点差2", DoubleToString(spread, 2), 10, "Consolas", clrDodgerBlue, CORNER_LEFT_UPPER, 85, 30);
        }
    }
    return false;
}

//+------------------------------------------------------------------+
//| 计算超级趋势值函数        最高点到上一根收盘价 / 最高点到最低点 (箱体长度)
//| 取值区间   由底部到高处（-100,0）                                         |
//+------------------------------------------------------------------+
double CalculateSuperTrend(double speedHigh, double close, double speedHigh1, double speedLow1)
{
    // Print("high: ", high, " close: ", close, " high2: ", high2, " low: ", low," result: ", (high - close) * (-100.0) / (high2 - low));
    return (speedHigh - close) * (-100.0) / (speedHigh1 - speedLow1);
}

//+------------------------------------------------------------------+
//| 自定义函数                                                         |
//+------------------------------------------------------------------+
// 其他函数将在这里实现 

//+------------------------------------------------------------------+
//| 检查多单开仓条件 (原ChaoNeng2)                                    |
//+------------------------------------------------------------------+
bool CheckBuyEntry(double closePrice, double lowPrice, double speedLowPrice)
{
    //总结 买单： 当前价格减去最低价格 要大于 波动因子*点数 前一根收盘价距离大箱体底部【波动因子】
    // 小箱体： 当前价格位于小箱体底部0-10位置 
    // 上一根收盘价 要小于等于 小箱体最低价
    
    // 计算大箱体高度
    double boxHeight = g_adaptiveHigh - g_adaptiveLow;
    double volatilityThreshold = boxHeight * (VolatilityFactor / 100.0);
    
    
    Print("CheckBuyEntry====> [买] volatilityThreshold: ", DoubleToString(volatilityThreshold, 2), " closePrice - lowPrice: ", DoubleToString(closePrice - lowPrice, 2));
    Print("CheckBuyEntry====> [买] g_superTrendValue: ", DoubleToString(g_superTrendValue, 2), " [speedLowPrice > closePrice]: ", (speedLowPrice > closePrice) ? "true" : "false");

    if(!g_tradeEnabled || g_buyOrders >= 1 || 
       volatilityThreshold >= closePrice - lowPrice  /*当前收盘价到最低价小于波动率因子不开仓*/||
       (double)(OpenPositionFactor - 100) < g_superTrendValue|| speedLowPrice <= closePrice ||
       (double)g_currentTime > g_expiryDate)
    {
        return false;
    }
    return true;
}

//+------------------------------------------------------------------+
//| 检查空单开仓条件 (原ChaoNeng3)                                    |
//+------------------------------------------------------------------+
bool CheckSellEntry(double highPrice, double closePrice, double speedHighPrice)
{
    // 卖单： 最高价格减去当前价格 要大于 波动因子*点数  前一根收盘价距离大箱体顶部【波动因子】
    // 小箱体： 当前价格位于小箱体顶部部0-10位置 
    // 上一根收盘价 要大于等于 小箱体最高价

    // 计算大箱体高度
    double boxHeight = g_adaptiveHigh - g_adaptiveLow;
    double volatilityThreshold = boxHeight * (VolatilityFactor / 100.0);

    Print("CheckSellEntry===> [卖] volatilityThreshold: ", DoubleToString(volatilityThreshold, 2), " highPrice - closePrice: ", DoubleToString(highPrice - closePrice, 2));
    Print("CheckSellEntry===> [卖] g_superTrendValue: ", DoubleToString(g_superTrendValue, 2), " [highPrice - closePrice]: ", DoubleToString(highPrice - closePrice, 2), " [speedLowPrice < closePrice]: ", (speedHighPrice < closePrice) ? "true" : "false", " result: true" );

    if(!g_tradeEnabled || g_sellOrders >= 1 || 
       volatilityThreshold >= highPrice - closePrice  /*最高价到当前收盘价小于波动率因子不开仓*/||
       (double)-OpenPositionFactor > g_superTrendValue || speedHighPrice >= closePrice /*小箱体的最高价大于收盘价不开仓*/||
       (double)g_currentTime > g_expiryDate)
    {
        return false;
    }
    return true;
}

//+------------------------------------------------------------------+
//| 检查多单二次开仓条件 (原ChaoNeng4)                                |
//+------------------------------------------------------------------+
bool CheckBuySecondEntry(double closePrice, double highPrice, double lowPrice, double lowPrice2, double bid)
{
    //买单加仓条件
    //1. 当前交易状态  允许交易
    //2. 当前持仓手数  小于5手
    //3. 当前开仓价格  当前买入价距离收盘价大于3个大点
    //4. 当前收盘价  收盘价要大于大箱体的 四分之一位置

    if(!g_tradeEnabled || g_buyOrders >= 5 || g_buyOpenPrice <= 0.0 ||
       (double)(3 * g_pointValue) * g_minLot >= closePrice - bid ||
       0.5 * ((highPrice + lowPrice) * 0.5 + lowPrice2) >= closePrice ||
       (double)g_currentTime > g_expiryDate)
    {
        return false;
    }
    return true;
}

//+------------------------------------------------------------------+
//| 检查空单二次开仓条件 (原ChaoNeng5)                                |
//+------------------------------------------------------------------+
bool CheckSellSecondEntry(double closePrice, double highPrice, double lowPrice, double highPrice2, double ask)
{
    //卖单加仓条件
    //1. 当前交易状态  允许交易
    //2. 当前持仓手数  小于5手
    //3. 当前开仓价格  当前卖出价距离收盘价大于3个大点
    //4. 当前收盘价  收盘价要小于大箱体的 四分之三位置


    if(!g_tradeEnabled || g_sellOrders >= 5 || g_sellOpenPrice <= 0.0 ||
       (double)(3 * g_pointValue) * g_minLot >= ask - closePrice ||
       0.5 * ((highPrice + lowPrice) * 0.5 + highPrice2) <= closePrice ||
       (double)g_currentTime > g_expiryDate)
    {
        return false;
    }
    return true;
}

//+------------------------------------------------------------------+
//| 检查多单平仓条件 (原ChaoNeng6)                                      |
//+------------------------------------------------------------------+
bool CheckBuyClose(int buyOrders, double closePrice, double speedHighPrice,
                  double superTrendValue, int closeFactor, datetime currentTime,
                  int retryLimit1, int retryLimit2, int retryLimit3, int retryLimit4, datetime expiryTime)
{
    if(buyOrders <= 0 || speedHighPrice >= closePrice ||
       (double)-closeFactor > superTrendValue || (double)currentTime > expiryTime)
    {
        return false;
    }
    return true;
}

//+------------------------------------------------------------------+
//| 检查空单平仓条件 (原ChaoNeng7)                                      |
//+------------------------------------------------------------------+
bool CheckSellClose(int sellOrders, double closePrice, double speedLowPrice,
                   double superTrendValue, int closeFactor, datetime currentTime,
                   int retryLimit1, int retryLimit2, int retryLimit3, int retryLimit4, datetime expiryTime)
{
    if(sellOrders <= 0 || speedLowPrice <= closePrice ||
       (double)(closeFactor - 100) < superTrendValue || (double)currentTime > expiryTime)
    {
        return false;
    }
    return true;
}

//+------------------------------------------------------------------+
//| 检查多单盈利平仓条件 (原ChaoNeng8)                                  |
//+------------------------------------------------------------------+
bool CheckBuyProfitClose(int buyOrders, double closePrice, double buyOpenPrice,
                        int profitFactor, int pointValue, double minLot, datetime currentTime,
                        int retryLimit1, int retryLimit2, int retryLimit3, int retryLimit4, datetime expiryTime)
{
    if(buyOrders <= 0 || (double)(pointValue * profitFactor) * minLot + buyOpenPrice >= closePrice ||
       (double)currentTime > expiryTime)
    {
        return false;
    }
    return true;
}

//+------------------------------------------------------------------+
//| 检查空单盈利平仓条件 (原ChaoNeng9)                                  |
//+------------------------------------------------------------------+
bool CheckSellProfitClose(int sellOrders, double closePrice, double sellOpenPrice,
                         int profitFactor, int pointValue, double minLot, datetime currentTime,
                         int retryLimit1, int retryLimit2, int retryLimit3, int retryLimit4, datetime expiryTime)
{
    if(sellOrders <= 0 || sellOpenPrice - (double)(pointValue * profitFactor) * minLot <= closePrice ||
       (double)currentTime > expiryTime)
    {
        return false;
    }
    return true;
}

//+------------------------------------------------------------------+
//| 检查多单二次平仓条件 (原ChaoNeng10)                                 |
//+------------------------------------------------------------------+
bool CheckBuySecondClose(int buyOrders, double buyProfit, double superTrendValue,
                        int closeFactor2, datetime currentTime, int retryLimit1, int retryLimit2,
                        int retryLimit3, int retryLimit4, datetime expiryTime)
{
    if(buyOrders <= 0 || buyProfit <= 0.0 || (double)-closeFactor2 > superTrendValue ||
       (double)currentTime > expiryTime)
    {
        return false;
    }
    return true;
}

//+------------------------------------------------------------------+
//| 检查空单二次平仓条件 (原ChaoNeng11)                                 |
//+------------------------------------------------------------------+
bool CheckSellSecondClose(int sellOrders, double sellProfit, double superTrendValue,
                         int closeFactor2, datetime currentTime, int retryLimit1, int retryLimit2,
                         int retryLimit3, int retryLimit4, datetime expiryTime)
{
    if(sellOrders <= 0 || sellProfit <= 0.0 || (double)(closeFactor2 - 100) < superTrendValue ||
       (double)currentTime > expiryTime)
    {
        return false;
    }
    return true;
}

//+------------------------------------------------------------------+
//| 开多单函数                                                         |
//+------------------------------------------------------------------+
void OpenBuy()
{
    double highPrice;
    double lowPrice;
    bool modifyResult = false;
    
    // 初始化变量
    g_orderTicket = -1;
    g_retryCount = 0;
    g_buyLot = 0;
    g_stopLossPrice = 0;
    g_takeProfit = 0;
    g_buyOpenTime = g_currentTime;
    
    // 获取高低点
    highPrice = iHigh(_Symbol, PERIOD_CURRENT, iHighest(_Symbol, PERIOD_CURRENT, MODE_HIGH, AdaptiveFactor, 2));
    lowPrice = iLow(_Symbol, PERIOD_CURRENT, iLowest(_Symbol, PERIOD_CURRENT, MODE_LOW, AdaptiveFactor, 2));
    
    // 设置止损价格
    if(AsianSessionSwitch)
    {
        g_stopLossPrice = NormalizeDouble(g_ask - StopLoss * g_pointValue * g_minLot, _Digits);
    }
    else
    {
        g_stopLossPrice = NormalizeDouble(lowPrice, _Digits);
    }
    
    // 计算交易手数
    if(RiskSwitch)
    {
        g_buyLot = NormalizeDouble(AccountInfoDouble(ACCOUNT_EQUITY) * RiskPercent / 1000000, 2);
    }
    else
    {
        g_buyLot = LotSize;
    }
    
    // 动态手数调整
    if(g_ask - lowPrice > g_pointValue * 110 * g_minLot && DynamicSwitch && !AsianSessionSwitch)
    {
        g_buyLot *= 1.6;
    }
    
    // 限制手数范围
    if(g_buyLot > 50) g_buyLot = 50;
    if(g_buyLot < 0.01) g_buyLot = 0.01;
    
    // 如果已有订单则返回
    if(g_orderTicket >= 0) return;
    
    // 尝试下单
    while(g_retryCount < 3)
    {
        g_stopLossPrice = g_stopLossPrice;
        g_takeProfit = NormalizeDouble(highPrice - lowPrice + (highPrice + lowPrice) / 2, _Digits);
        
        // 创建交易请求
        MqlTradeRequest request = {};
        MqlTradeResult result = {};
        
        request.action = TRADE_ACTION_DEAL;
        request.symbol = _Symbol;
        request.volume = g_buyLot;
        request.type = ORDER_TYPE_BUY;
        request.price = g_ask;
        request.sl = g_stopLossPrice;
        request.tp = g_takeProfit;
        request.deviation = g_slippage * g_pointValue;
        request.magic = g_magicNumber;
        request.comment = EAComment;
        request.type_filling = ORDER_FILLING_FOK;
        
        // 发送交易请求
        if(!OrderSend(request, result))
        {
            Print("下单错误 = ", GetLastError());
        }
        else
        {
            g_orderTicket = result.order;
            
            // 如果设置了止损止盈，尝试修改订单
            if(g_orderTicket > 0 && (g_stopLossPrice != 0 || g_takeProfit != 0))
            {
                request.action = TRADE_ACTION_SLTP;
                request.position = g_orderTicket;
                request.sl = g_stopLossPrice;
                request.tp = g_takeProfit;
                
                if(!OrderSend(request, result))
                {
                    Print("设置止损止盈失败 = ", GetLastError());
                }
            }
        }
        
        Sleep(1000);
        g_retryCount++;
        if(g_orderTicket >= 0) return;
    }
}

//+------------------------------------------------------------------+
//| 开空单函数                                                         |
//+------------------------------------------------------------------+
void OpenSell()
{
    double highPrice;
    double lowPrice;
    bool modifyResult = false;
    
    // 初始化变量
    g_orderTicket = -1;
    g_retryCount = 0;
    g_sellLot = 0;
    g_stopLossPrice = 0;
    g_takeProfit = 0;
    g_sellOpenTime = g_lastBarTime;
    
    // 获取高低点
    highPrice = iHigh(_Symbol, PERIOD_CURRENT, iHighest(_Symbol, PERIOD_CURRENT, MODE_HIGH, AdaptiveFactor, 2));
    lowPrice = iLow(_Symbol, PERIOD_CURRENT, iLowest(_Symbol, PERIOD_CURRENT, MODE_LOW, AdaptiveFactor, 2));
    
    // 设置止损价格
    if(AsianSessionSwitch)
    {
        g_stopLossPrice = NormalizeDouble(StopLoss * g_pointValue * g_minLot + g_bid, _Digits);
    }
    else
    {
        g_stopLossPrice = NormalizeDouble(highPrice, _Digits);
    }
    
    // 计算交易手数
    if(RiskSwitch)
    {
        g_sellLot = NormalizeDouble(AccountInfoDouble(ACCOUNT_EQUITY) * RiskPercent / 1000000, 2);
    }
    else
    {
        g_sellLot = LotSize;
    }
    
    // 动态手数调整
    if(highPrice - g_spreadValue > g_pointValue * 110 * g_minLot && DynamicSwitch && !AsianSessionSwitch)
    {
        g_sellLot *= 1.6;
    }
    
    // 限制手数范围
    if(g_sellLot > 50) g_sellLot = 50;
    if(g_sellLot < 0.01) g_sellLot = 0.01;
    
    // 如果已有订单则返回
    if(g_orderTicket >= 0) return;
    
    // 尝试下单
    while(g_retryCount < 3)
    {
        g_stopLossPrice = g_stopLossPrice;
        g_takeProfit = NormalizeDouble((highPrice + lowPrice) / 2 - (highPrice - lowPrice), _Digits);
        
        // 创建交易请求
        MqlTradeRequest request = {};
        MqlTradeResult result = {};
        
        request.action = TRADE_ACTION_DEAL;
        request.symbol = _Symbol;
        request.volume = g_sellLot;
        request.type = ORDER_TYPE_SELL;
        request.price = g_bid;
        request.sl = g_stopLossPrice;
        request.tp = g_takeProfit;
        request.deviation = g_slippage * g_pointValue;
        request.magic = g_magicNumber;
        request.comment = EAComment;
        request.type_filling = ORDER_FILLING_FOK;
        
        // 发送交易请求
        if(!OrderSend(request, result))
        {
            Print("下单错误 = ", GetLastError());
        }
        else
        {
            g_orderTicket = result.order;
            
            // 如果设置了止损止盈，尝试修改订单
            if(g_orderTicket > 0 && (g_stopLossPrice != 0 || g_takeProfit != 0))
            {
                request.action = TRADE_ACTION_SLTP;
                request.position = g_orderTicket;
                request.sl = g_stopLossPrice;
                request.tp = g_takeProfit;
                
                if(!OrderSend(request, result))
                {
                    Print("设置止损止盈失败 = ", GetLastError());
                }
            }
        }
        
        Sleep(1000);
        g_retryCount++;
        if(g_orderTicket >= 0) return;
    }
}

//+------------------------------------------------------------------+
//| 统计交易函数                                                       |
//+------------------------------------------------------------------+
void CountTrades()
{
    g_buyOrders = 0;
    g_sellOrders = 0;
    g_buyVolume = 0;
    g_sellVolume = 0;
    g_buyProfit = 0;
    g_sellProfit = 0;
    g_totalProfit = 0;
    g_totalVolume = 0;
    
    // 遍历所有持仓
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if(PositionSelectByTicket(PositionGetTicket(i)))
        {
            if(PositionGetString(POSITION_SYMBOL) == _Symbol && 
               PositionGetInteger(POSITION_MAGIC) == g_magicNumber)
            {
                double volume = PositionGetDouble(POSITION_VOLUME);
                double profit = PositionGetDouble(POSITION_PROFIT);
                
                if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    g_buyOrders++;
                    g_buyVolume += volume;
                    g_buyProfit += profit;
                    g_buyOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
                }
                else if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    g_sellOrders++;
                    g_sellVolume += volume;
                    g_sellProfit += profit;
                    g_sellOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
                }
                
                g_totalVolume += volume;
                g_totalProfit += profit;
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 平多单函数                                                         |
//+------------------------------------------------------------------+
void CloseBuyOrders()
{
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if(PositionSelectByTicket(PositionGetTicket(i)))
        {
            if(PositionGetString(POSITION_SYMBOL) == _Symbol && 
               PositionGetInteger(POSITION_MAGIC) == g_magicNumber &&
               PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                MqlTradeRequest request = {};
                MqlTradeResult result = {};
                
                request.action = TRADE_ACTION_DEAL;
                request.position = PositionGetTicket(i);
                request.symbol = _Symbol;
                request.volume = PositionGetDouble(POSITION_VOLUME);
                request.type = ORDER_TYPE_SELL;
                request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
                request.deviation = g_slippage * g_pointValue;
                request.magic = g_magicNumber;
                request.comment = EAComment;
                request.type_filling = ORDER_FILLING_FOK;
                
                if(!OrderSend(request, result))
                {
                    Print("平多单失败 = ", GetLastError());
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 平空单函数                                                         |
//+------------------------------------------------------------------+
void CloseSellOrders()
{
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if(PositionSelectByTicket(PositionGetTicket(i)))
        {
            if(PositionGetString(POSITION_SYMBOL) == _Symbol && 
               PositionGetInteger(POSITION_MAGIC) == g_magicNumber &&
               PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                MqlTradeRequest request = {};
                MqlTradeResult result = {};
                
                request.action = TRADE_ACTION_DEAL;
                request.position = PositionGetTicket(i);
                request.symbol = _Symbol;
                request.volume = PositionGetDouble(POSITION_VOLUME);
                request.type = ORDER_TYPE_BUY;
                request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
                request.deviation = g_slippage * g_pointValue;
                request.magic = g_magicNumber;
                request.comment = EAComment;
                request.type_filling = ORDER_FILLING_FOK;
                
                if(!OrderSend(request, result))
                {
                    Print("平空单失败 = ", GetLastError());
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 检查交易按钮状态                                                   |
//+------------------------------------------------------------------+
void CheckTradeButton()
{
    if(ObjectGetInteger(0, "TradeButton", OBJPROP_STATE))
    {
        ObjectSetInteger(0, "TradeButton", OBJPROP_STATE, false);
        g_tradeEnabled = !g_tradeEnabled;
        
        if(g_tradeEnabled)
        {
            ObjectSetString(0, "TradeButton", OBJPROP_TEXT, "交易开启");
            ObjectSetInteger(0, "TradeButton", OBJPROP_BGCOLOR, clrLime);
        }
        else
        {
            ObjectSetString(0, "TradeButton", OBJPROP_TEXT, "交易关闭");
            ObjectSetInteger(0, "TradeButton", OBJPROP_BGCOLOR, clrRed);
        }
    }
}

//+------------------------------------------------------------------+
//| 更新交易按钮状态                                                   |
//+------------------------------------------------------------------+
void UpdateTradeButton()
{
    if(g_tradeEnabled)
    {
        ObjectSetString(0, "TradeButton", OBJPROP_TEXT, "交易开启");
        ObjectSetInteger(0, "TradeButton", OBJPROP_BGCOLOR, clrLime);
    }
    else
    {
        ObjectSetString(0, "TradeButton", OBJPROP_TEXT, "交易关闭");
        ObjectSetInteger(0, "TradeButton", OBJPROP_BGCOLOR, clrRed);
    }
}

//+------------------------------------------------------------------+
//| 绘制箱体函数                                                       |
//+------------------------------------------------------------------+
void DrawBoxes()
{
    // 计算AdaptiveFactor箱体
    int adaptiveStartBar = AdaptiveFactor + 2;
    int adaptiveEndBar = 2;  // 当前K线-2
    
    datetime adaptiveStartTime = iTime(_Symbol, PERIOD_CURRENT, adaptiveStartBar);
    datetime adaptiveEndTime = iTime(_Symbol, PERIOD_CURRENT, adaptiveEndBar);
    
    // 创建AdaptiveFactor箱体
    if(!ObjectCreate(0, "AdaptiveBox", OBJ_RECTANGLE, 0, adaptiveStartTime, g_adaptiveHigh, adaptiveEndTime, g_adaptiveLow))
    {
        Print("创建AdaptiveFactor箱体失败: ", GetLastError());
    }
    else
    {
        ObjectSetInteger(0, "AdaptiveBox", OBJPROP_COLOR, C'128,128,128');
        ObjectSetInteger(0, "AdaptiveBox", OBJPROP_STYLE, STYLE_SOLID);
        ObjectSetInteger(0, "AdaptiveBox", OBJPROP_WIDTH, 1);
        ObjectSetInteger(0, "AdaptiveBox", OBJPROP_FILL, true);
        ObjectSetInteger(0, "AdaptiveBox", OBJPROP_BACK, true);
        ObjectSetInteger(0, "AdaptiveBox", OBJPROP_SELECTABLE, false);
        ObjectSetInteger(0, "AdaptiveBox", OBJPROP_SELECTED, false);
        ObjectSetInteger(0, "AdaptiveBox", OBJPROP_HIDDEN, true);
        ObjectSetInteger(0, "AdaptiveBox", OBJPROP_ZORDER, 0);
    }
    
    // 计算SpeedFactor箱体
    int speedStartBar = SpeedFactor + 1;
    int speedEndBar = 1;  // 当前K线-1
    
    double speedHigh = iHigh(_Symbol, PERIOD_CURRENT, iHighest(_Symbol, PERIOD_CURRENT, MODE_HIGH, SpeedFactor, 1));
    double speedLow = iLow(_Symbol, PERIOD_CURRENT, iLowest(_Symbol, PERIOD_CURRENT, MODE_LOW, SpeedFactor, 1));
    
    datetime speedStartTime = iTime(_Symbol, PERIOD_CURRENT, speedStartBar);
    datetime speedEndTime = iTime(_Symbol, PERIOD_CURRENT, speedEndBar);
    
    // 创建SpeedFactor箱体
    if(!ObjectCreate(0, "SpeedBox", OBJ_RECTANGLE, 0, speedStartTime, speedHigh, speedEndTime, speedLow))
    {
        Print("创建SpeedFactor箱体失败: ", GetLastError());
    }
    else
    {
        ObjectSetInteger(0, "SpeedBox", OBJPROP_COLOR, clrRed);
        ObjectSetInteger(0, "SpeedBox", OBJPROP_STYLE, STYLE_SOLID);
        ObjectSetInteger(0, "SpeedBox", OBJPROP_WIDTH, 1);
        ObjectSetInteger(0, "SpeedBox", OBJPROP_FILL, false);
        ObjectSetInteger(0, "SpeedBox", OBJPROP_BACK, true);
        ObjectSetInteger(0, "SpeedBox", OBJPROP_SELECTABLE, false);
        ObjectSetInteger(0, "SpeedBox", OBJPROP_SELECTED, false);
        ObjectSetInteger(0, "SpeedBox", OBJPROP_HIDDEN, true);
        ObjectSetInteger(0, "SpeedBox", OBJPROP_ZORDER, 1);
    }

    // 计算波动率阈值线
    double boxHeight = g_adaptiveHigh - g_adaptiveLow;
    double volatilityThreshold = boxHeight * (VolatilityFactor / 100.0);
    double buyThreshold = g_adaptiveLow + volatilityThreshold;
    double sellThreshold = g_adaptiveHigh - volatilityThreshold;

    // 绘制买入阈值线
    if(!ObjectCreate(0, "BuyThresholdLine", OBJ_HLINE, 0, 0, buyThreshold))
    {
        Print("创建买入阈值线失败: ", GetLastError());
    }
    else
    {
        ObjectSetInteger(0, "BuyThresholdLine", OBJPROP_COLOR, clrLime);
        ObjectSetInteger(0, "BuyThresholdLine", OBJPROP_STYLE, STYLE_DASH);
        ObjectSetInteger(0, "BuyThresholdLine", OBJPROP_WIDTH, 1);
        ObjectSetInteger(0, "BuyThresholdLine", OBJPROP_SELECTABLE, false);
        ObjectSetInteger(0, "BuyThresholdLine", OBJPROP_SELECTED, false);
        ObjectSetInteger(0, "BuyThresholdLine", OBJPROP_HIDDEN, true);
        ObjectSetInteger(0, "BuyThresholdLine", OBJPROP_ZORDER, 2);
    }

    // 绘制卖出阈值线
    if(!ObjectCreate(0, "SellThresholdLine", OBJ_HLINE, 0, 0, sellThreshold))
    {
        Print("创建卖出阈值线失败: ", GetLastError());
    }
    else
    {
        ObjectSetInteger(0, "SellThresholdLine", OBJPROP_COLOR, clrRed);
        ObjectSetInteger(0, "SellThresholdLine", OBJPROP_STYLE, STYLE_DASH);
        ObjectSetInteger(0, "SellThresholdLine", OBJPROP_WIDTH, 1);
        ObjectSetInteger(0, "SellThresholdLine", OBJPROP_SELECTABLE, false);
        ObjectSetInteger(0, "SellThresholdLine", OBJPROP_SELECTED, false);
        ObjectSetInteger(0, "SellThresholdLine", OBJPROP_HIDDEN, true);
        ObjectSetInteger(0, "SellThresholdLine", OBJPROP_ZORDER, 2);
    }

    // 添加波动率标签
    string volatilityText = "波动率阈值: " + DoubleToString(VolatilityFactor, 0) + "%";
    if(!ObjectCreate(0, "VolatilityLabel", OBJ_LABEL, 0, 0, 0))
    {
        Print("创建波动率标签失败: ", GetLastError());
    }
    else
    {
        ObjectSetString(0, "VolatilityLabel", OBJPROP_TEXT, volatilityText);
        ObjectSetInteger(0, "VolatilityLabel", OBJPROP_CORNER, CORNER_LEFT_UPPER);
        ObjectSetInteger(0, "VolatilityLabel", OBJPROP_XDISTANCE, 10);
        ObjectSetInteger(0, "VolatilityLabel", OBJPROP_YDISTANCE, 20);
        ObjectSetInteger(0, "VolatilityLabel", OBJPROP_COLOR, clrWhite);
        ObjectSetInteger(0, "VolatilityLabel", OBJPROP_FONTSIZE, 9);
        ObjectSetString(0, "VolatilityLabel", OBJPROP_FONT, "Arial");
    }
} 